<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2007/04/23 11:17:14 $)
// $RCSfile: winapp_chatloop.php,v $ : $Revision: 1.22 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

	

$messages = array();
$noloop = false;

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

headerNoCache();

$template->loadLanguageSection("livesupport");
require_once ("./modules/livesupport/functions_livesupport.php");

// Get the chat object data
$_chatobject = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."sessions` AS sessions LEFT JOIN `". TABLE_PREFIX ."chatobjects` AS chatobjects ON (sessions.typeid = chatobjects.chatobjectid) WHERE sessions.sessionid = '". $dbCore->escape($_GET["chatsessionid"]) ."';");

if ($_chatobject["chattype"] == CHAT_STAFF)
{
	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."sessions` SET `lastactivity` = '". DATENOW ."' WHERE `sessionid` IN('". $dbCore->escape($_GET["chatsessionid"]) ."');");
}

// Has it been more than 120 seconds since last update from client?
$timescale = DATENOW-120;
if ($_chatobject["lastactivity"] < $timescale)
{
	// Yes sir
	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."sessions` SET `lastactivity` = '". DATENOW ."' WHERE `sessionid` IN('". $dbCore->escape($_GET["chatsessionid"]) ."');");
	//$messagejs .= "displayNewLine();".SWIFT_CRLF;
	//$messagejs .= "displayMessage(\"". $_SWIFT["language"]["clientnoresponse"] ."\");".SWIFT_CRLF;
	
	$message = array(
		'type' => 'clientnoresponse',
		'from' => '',
		'content' => $_SWIFT["language"]["clientnoresponse"]
	);
	array_push($messages, $message);
}

if ($_chatobject["chatobjectid"] == "")
{
	// Stop the loop right here.
	$noloop = true;
	//$messagejs .= "displayNewLine();".SWIFT_CRLF;
	//$messagejs .= "displayMessage(\"". $_SWIFT["language"]["chatexpired"] ."\");".SWIFT_CRLF;
	
	$message = array(
		'type' => 'chatexpired',
		'from' => '',
		'content' => $_SWIFT["language"]["chatexpired"]
	);
	array_push($messages, $message);
}
//	$messagejs .= "displayMessage(\"if you see this then loop works\");".SWIFT_CRLF;

$messagelistids = $ignoreusers = array();
$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."messagequeue` WHERE `chatchildid` = '". $dbCore->escape($_GET["chatchildid"]) ."' AND `chatobjectid` = '". $dbCore->escape($_chatobject["chatobjectid"]) ."' ORDER BY `dateline` ASC;");

while ($dbCore->nextRecord())
{
	$messagelistids[] = $dbCore->Record["messagequeueid"];
	$msgarray = unserialize($dbCore->Record["contents"]);
	if (is_array($msgarray)) {
		if ($msgarray["type"] == "message")
		{
			if (!in_array($dbCore->Record["staffid"], $ignoreusers))
			{
				$ignoreusers[] = $dbCore->Record["staffid"];
			}

			unset($_message);
			if ($msgarray["base64"] == true)
			{
				$_message = $msgarray["contents"];
			} else {
				$_message = base64_encode($msgarray["contents"]);
			}

			//$messagejs .= "writeToDiv(\"<span class='clientname'>". addslashes(preg_replace('/&amp;#(x[a-f0-9]+|[0-9]+);/i', '&#$1;', htmlspecialchars($dbCore->Record["name"]))) .":</span><span class='clientmessage'>&nbsp;\"+decode64(\"". addslashes($_message) ."\") + \"</span><BR />\"); \n";
			
			$message = array(
				'type' => 'message',
				'from' => addslashes(preg_replace('/&amp;#(x[a-f0-9]+|[0-9]+);/i', '&#$1;', htmlspecialchars($dbCore->Record["name"]))),
				'content' => addslashes($_message)
			);
			array_push($messages, $message);
			
		} else if ($msgarray["type"] == "image") {
			//$messagejs .= "pushImage(\"".addslashes($msgarray["contents"]) ."\"); \n";
			$message = array(
				'type' => 'image',
				'from' => '',
				'content' => $msgarray["contents"]
			);
			array_push($messages, $message);
		} else if ($msgarray["type"] == "code") {
			//$messagejs .= "pushStart();".SWIFT_CRLF;
			//$messagejs .= HTML2JS(highlightCode($msgarray["contents"]), "pushCode");
			//$messagejs .= "pushEnd();".SWIFT_CRLF;
			$message = array(
				'type' => 'code',
				'from' => '',
				'content' => $msgarray["contents"]
			);
		} else if ($msgarray["type"] == ACTION_CHATLEAVE) {
			// Staff left the chat from conference
			//$messagejs .= "displayNewLine();".SWIFT_CRLF;
			//$messagejs .= "displayMessage(\"". addslashes(sprintf($_SWIFT["language"]["chatleave"], $msgarray["contents"])) ."\");".SWIFT_CRLF;
			$message = array(
				'type' => ACTION_CHATLEAVE,
				'from' => '',
				'content' => $msgarray["contents"]
			);
			array_push($messages, $message);
		} else if ($msgarray["type"] == ACTION_CHATENTER) {
			//$messagejs .= "displayNewLine();".SWIFT_CRLF;
			//$messagejs .= "displayMessage(\"". addslashes(sprintf($_SWIFT["language"]["chatenter"], $msgarray["contents"])) ."\");".SWIFT_CRLF;
			$message = array(
				'type' => ACTION_CHATENTER,
				'from' => '',
				'content' => $msgarray["contents"]
			);
			array_push($messages, $message);
		} else if ($msgarray["type"] == ACTION_TYPING) {
			//$_typingname = $msgarray["contents"];
			//$_typinguser = $dbCore->Record["staffid"];
			$message = array(
				'type' => ACTION_TYPING,
				'from' => $dbCore->Record["staffid"],
				'content' => $msgarray["contents"]
			);
			array_push($messages, $message);
/*		} else if ($msgarray["type"] == ACTION_VOICECHAT) {
			$messagejs .= "startVoiceChat('". addslashes($msgarray["contents"]["ip"]) ."', '". addslashes($msgarray["contents"]["port"]) ."');".SWIFT_CRLF;
			$messagejs .= "displayNewLine();".SWIFT_CRLF;
			$messagejs .= "displayMessage(\"". addslashes(sprintf($_SWIFT["language"]["startingvoicechat"], $dbCore->Record["name"], $msgarray["contents"]["ip"])) ."\");".SWIFT_CRLF;*/
		} else if ($msgarray["type"] == ACTION_VIEWSHARE) {
			//$messagejs .= "startViewShare('". addslashes($msgarray["contents"]["url"]) ."');".SWIFT_CRLF;
			//$messagejs .= "displayMessage(\"". addslashes(sprintf($_SWIFT["language"]["startingstaffviewshare"], $msgarray["contents"]["name"])) ."\");".SWIFT_CRLF;
			$message = array(
				'type' => ACTION_VIEWSHARE,
				'from' => '',
				'content' => $msgarray["contents"]
			);
		}
	}
}


if ($_chatobject["chatstatus"] == CHAT_ENDED)
{
	if ($_chatobject["staffid"] == $_SWIFT["staff"]["staffid"] && $_chatobject["chattype"] == CHAT_STAFF)
	{
		$_fullname = $_chatobject["userfullname"];
	} else if ($_chatobject["userid"] == $_SWIFT["staff"]["staffid"] && $_chatobject["chattype"] == CHAT_STAFF) {
		$_fullname = $_chatobject["staffname"];
	} else {
		$_fullname = $_chatobject["userfullname"];
	}

	$noloop = true;
	//$messagejs .= "displayNewLine();".SWIFT_CRLF;
	//$messagejs .= "displayMessage(\"". addslashes(sprintf($_SWIFT["language"]["chatleave"], $_fullname)) ."\");".SWIFT_CRLF;
	$message = array(
		'type' => 'chatend',
		'from' => $_fullname,
		'content' => ''
	);
	array_push($messages, $message);
}

if (count($messagelistids) > 0)
{
	$dbCore->shutdownQuery("DELETE FROM `". TABLE_PREFIX ."messagequeue` WHERE `messagequeueid` IN (". buildIN($messagelistids) .");");
}


require_once ("./includes/functions_xml.php");
$xml = new XML;
$xml->addParentTag("swiftwinapp");
$xml->addTag("noloop", $noloop);
$xml->addTag("chatsessionid", $_GET["chatsessionid"]);
foreach ($messages as $msg) {
	$xml->addParentTag("message");
		$xml->addTag("type", $msg['type']);
		$xml->addTag("from", $msg['from']);
		$xml->addTag("content", $msg['content']);
	$xml->endTag("message");
}
$xml->endTag("swiftwinapp");
$xml->echoXMLUTFWinapp();
